import { _decorator, Button, Component, EditBox, Enum, error, JsonAsset, Label, Node, resources, Sprite, Toggle, UIOpacity, } from 'cc';
import { generateUpperCaseLetters, loadJson, shuffleArray } from '../../utils/func';
import { choice, range } from '../../utils/python_func'
import { isAllowNextStep, NodeName } from '../../utils/common';
import { VerifyRealPerson } from '../VerifyRealPerson';
const { ccclass, property } = _decorator;


@ccclass('FloatControlBar')
export class FloatControlBar extends Component {
    private next_question_button: Node = null;    // 下一题按钮
    private verify_real_person_button: Node = null;
    private verify_real_person_sprite: Node = null;
    private title_answer_analysis_sprite: Node = null;
    private title_button: Node = null;
    private option_button: Node = null;
    private options_node: Node = null;
    private answer_button: Node = null;
    private analysis_button: Node = null;
    private statistics_answer_button: Node = null;     // 统计问题按钮
    private current_rank_button: Node = null;     // 本题排名按钮
    private total_rank_button: Node = null;     // 累积排名按钮

    private RightAnswerLetter: string = null;

    protected start(): void {
        resources.load('/data/question-bank/历史/秦朝/题库', (err: any, res: JsonAsset) => {
            if (err) {
                error(err.message || err);
                return;
            }
            // 获取到 Json 数据
            localStorage.setItem('QuestionBank', JSON.stringify(res.json!))
        })
    }

    protected onLoad(): void {
        // ------------------对脚本中将会用到的节点进行初始化，方便使用----------------
        this.next_question_button = this.node.getChildByName(NodeName.LiveRoomScene.Button.NextQuestionButton);
        this.verify_real_person_button = this.node.getChildByName(NodeName.LiveRoomScene.Button.VerifyRealPersonButton);
        this.verify_real_person_sprite = this.node.parent.getChildByName(NodeName.LiveRoomScene.Sprite.VerifyRealPersonSprite);
        this.title_answer_analysis_sprite = this.node.parent.getChildByName(NodeName.LiveRoomScene.Node.BlackBoardsNode).getChildByName(NodeName.LiveRoomScene.Sprite.TitleAnswerAnalysisSprite);
        this.title_button = this.node.getChildByName(NodeName.LiveRoomScene.Button.TitleButton);
        this.option_button = this.node.getChildByName(NodeName.LiveRoomScene.Button.OptionButton);
        this.options_node = this.node.parent.getChildByName(NodeName.LiveRoomScene.Node.BlackBoardsNode).getChildByName(NodeName.LiveRoomScene.Node.OptionsNode);
        this.answer_button = this.node.getChildByName(NodeName.LiveRoomScene.Button.AnswerButton);
        this.analysis_button = this.node.getChildByName(NodeName.LiveRoomScene.Button.AnalysisButton);
        this.statistics_answer_button = this.node.getChildByName(NodeName.LiveRoomScene.Button.StatisticsAnswerButton);
        this.current_rank_button = this.node.getChildByName(NodeName.LiveRoomScene.Button.CurrentRankButton);
        this.total_rank_button = this.node.getChildByName(NodeName.LiveRoomScene.Button.TotalRankButton);

        // --------------------绑定节点的函数-------------------
        this.next_question_button.on(Button.EventType.CLICK, this.onNextQuestionButtonClick, this);
        this.verify_real_person_button.on(Button.EventType.CLICK, this.onVerifyRealPersonButtonClick, this);
        this.title_button.on(Button.EventType.CLICK, this.onTitleButtonClick, this);
        this.option_button.on(Button.EventType.CLICK, this.onOptionButtonClick, this);
        this.answer_button.on(Button.EventType.CLICK, this.onAnswerButtonClick, this);
        this.analysis_button.on(Button.EventType.CLICK, this.onAnalysisButtonClick, this);
        this.statistics_answer_button.on(Button.EventType.CLICK, this.onStatisticsAnswerButtonClick, this);
        this.current_rank_button.on(Button.EventType.CLICK, this.onCurrentRankButtonClick, this);
        this.total_rank_button.on(Button.EventType.CLICK, this.onTotalRankButtonClick, this);

        console.log('火锅：', this.title_answer_analysis_sprite);
    }

    protected onDestroy(): void {
        // ----------------取消节点绑定的函数---------------
        this.next_question_button.off(Button.EventType.CLICK, this.onNextQuestionButtonClick, this);
        this.verify_real_person_button.off(Button.EventType.CLICK, this.onVerifyRealPersonButtonClick, this);
        this.title_button.off(Button.EventType.CLICK, this.onTitleButtonClick, this);
        this.option_button.off(Button.EventType.CLICK, this.onOptionButtonClick, this);
        this.answer_button.off(Button.EventType.CLICK, this.onAnswerButtonClick, this);
        this.analysis_button.off(Button.EventType.CLICK, this.onAnalysisButtonClick, this);
        this.statistics_answer_button.off(Button.EventType.CLICK, this.onStatisticsAnswerButtonClick, this);
        this.current_rank_button.off(Button.EventType.CLICK, this.onCurrentRankButtonClick, this);
        this.total_rank_button.off(Button.EventType.CLICK, this.onTotalRankButtonClick, this);
    }
    
    onNextQuestionButtonClick() {
        /**
         * 下一题按钮点击事件
         * 1. 随机从本地题库中获取一道题，创建本场PK的数据文件中。
         * 2. 获取成功后需要在前端提醒。
        */
        const _Step = "NextQuestion";
        if (isAllowNextStep(localStorage.getItem('GameStep'), _Step)) {
            let question_bank = JSON.parse(localStorage.getItem('QuestionBank'));
            let current_question= choice(question_bank);
            if (localStorage.getItem('current_question') !== current_question) {
                localStorage.setItem('current_question', JSON.stringify(current_question));
            }
            // 需要重置上一题的节点信息
            this.onResetVerifyRealPerson();
            this.onResetTitle();
            this.onResetOptions();
            this.onResetAnswer();
            this.onResetAnalysis();
            // 当本步骤完成时，需要将当前步骤名称赋值给GameStep
            localStorage.setItem('GameStep', _Step);
        } else {
            // throw new Error("请根据按钮顺序逐步操作");
        }
    }

    onVerifyRealPersonButtonClick() {
        const _Step = "VerifyRealPerson";
        if (isAllowNextStep(localStorage.getItem('GameStep'), _Step)) {
            // this.verify_real_person_sprite.node.active = true;
            this.verify_real_person_sprite.active = true;
            // 当本步骤完成时，需要将当前步骤名称赋值给GameStep
            localStorage.setItem('GameStep', _Step);
        } else {
            // throw new Error("请根据按钮顺序逐步操作");
        }
    }

    onResetVerifyRealPerson() {
        /**
         * 重置真人验证信息
        */
        // 初始化真人验证模板里面的初始值。
        VerifyRealPerson.initVerifyRealPerson(this.verify_real_person_sprite);
        this.verify_real_person_sprite.active = false;
    }

    onTitleButtonClick() {
        const _Step = "Title";
        if (isAllowNextStep(localStorage.getItem('GameStep'), _Step)) {
            this.verify_real_person_sprite.active = false;
            let current_question = JSON.parse(localStorage.getItem('current_question'));
            this.title_answer_analysis_sprite.getChildByName(NodeName.LiveRoomScene.Label.TitleLabel).getComponent(Label).string = current_question['title'];
            // this.black_board.getChildByName('TitleLabel').getComponent(Label).string = current_question['title'];
            // this.black_board.active = true;
            this.title_answer_analysis_sprite.active = true;
            localStorage.setItem('GameStep', _Step);
        } else {
            // throw new Error("请根据按钮顺序逐步操作");
        }
    }

    onResetTitle() {
        /**
         * 重置题干信息
        */
        this.title_answer_analysis_sprite.getChildByName(NodeName.LiveRoomScene.Label.TitleLabel).getComponent(Label).string = "";
        this.title_answer_analysis_sprite.active = false;
    }

    onOptionButtonClick() {
        const _Step = "Option";
        if (isAllowNextStep(localStorage.getItem('GameStep'), _Step)) {
            let current_question = JSON.parse(localStorage.getItem('current_question'));
            let options_info = shuffleArray(current_question['options']);
            let letters = generateUpperCaseLetters(4);
            for (let i =0; i<= this.options_node.children.length-1; i++) {
                let options_string = `${letters[i]}: ${options_info[i]}`
                this.options_node.children[i].getChildByName('Label').getComponent(Label).string = options_string;
                if (options_info[i] === current_question['answer']) {
                    this.RightAnswerLetter = letters[i];
                };
            }
            localStorage.setItem('GameStep', _Step);
        } else {
            // throw new Error("请根据按钮顺序逐步操作");
        }
    }

    onResetOptions() {
        /**
         * 重置选项信息
        */
        this.options_node.children.forEach((item) => {
            item.getChildByName('Label').getComponent(Label).string = "";
        })
    }

    onAnswerButtonClick() {
        const _Step = "Answer";
        if (isAllowNextStep(localStorage.getItem('GameStep'), _Step)) {
            let current_question = JSON.parse(localStorage.getItem('current_question'));
            this.title_answer_analysis_sprite.getChildByName(NodeName.LiveRoomScene.Label.AnswerLabel).getComponent(Label).string = `${this.RightAnswerLetter}:${current_question['answer']}`;
            localStorage.setItem('GameStep', _Step);
        } else {
            // throw new Error("请根据按钮顺序逐步操作");
        }
    }

    onResetAnswer() {
        /**
         * 重置答案信息
        */
        this.title_answer_analysis_sprite.getChildByName(NodeName.LiveRoomScene.Label.AnswerLabel).getComponent(Label).string = "";
    }

    onAnalysisButtonClick() {
        const _Step = "Analysis";
        if (isAllowNextStep(localStorage.getItem('GameStep'), _Step)) {
            let current_question = JSON.parse(localStorage.getItem('current_question'));
            this.title_answer_analysis_sprite.getChildByName(NodeName.LiveRoomScene.Label.AnalysisLabel).getComponent(Label).string = current_question['analysis'];
            localStorage.setItem('GameStep', _Step);
        } else {
            // throw new Error("请根据按钮顺序逐步操作");
        }
    }

    onResetAnalysis() {
        /**
         * 重置解析信息
        */
        this.title_answer_analysis_sprite.getChildByName(NodeName.LiveRoomScene.Label.AnalysisLabel).getComponent(Label).string = "";
    }

    onStatisticsAnswerButtonClick() {
        const _Step = "StatisticsAnswer";
        if (isAllowNextStep(localStorage.getItem('GameStep'), _Step)) {
            // 向直播平台发送请求获取答题的弹幕信息
            localStorage.setItem('GameStep', _Step);
        } else {
            // throw new Error("请根据按钮顺序逐步操作");
        }
    }

    onResetStatisticsAnswer() {
        /**
         * 重置统计问题按钮
        */
    }

    onCurrentRankButtonClick() {
        const _Step = "CurrentRank";
        if (isAllowNextStep(localStorage.getItem('GameStep'), _Step)) {
            // 根据存储在本地的玩家答题数据进行计算，得出本题的玩家排名名单
            localStorage.setItem('GameStep', _Step);
        } else {
            // throw new Error("请根据按钮顺序逐步操作");
        }
    }

    onResetCurrentRank() {
        /**
         * 重置本题排名信息
        */
        // this.title_answer_analysis_sprite.getChildByName(NodeName.LiveRoomScene.Label.AnalysisLabel).getComponent(Label).string = "";
    }

    onTotalRankButtonClick() {
        const _Step = "TotalRank";
        if (isAllowNextStep(localStorage.getItem('GameStep'), _Step)) {
            localStorage.setItem('GameStep', _Step);
        } else {
            // throw new Error("请根据按钮顺序逐步操作");
        }
    }

    onResetTotalRank() {
        /**
         * 重置累积排名信息
        */
        // this.title_answer_analysis_sprite.getChildByName(NodeName.LiveRoomScene.Label.AnalysisLabel).getComponent(Label).string = "";
    }
}


